import React from 'react'; 
import { Button, message } from 'antd';
// import AceEditor from 'react-ace';
import { isEqual } from 'lodash';
var prettyJSONStringify = require('pretty-json-stringify');
import {
    WeaErrorPage,
    WeaTools,
    WeaDialog,
    WeaLeftRightLayout,
    WeaRightMenu,
    WeaEchart,
    WeaTextarea,
    WeaInput,
    WeaLocaleProvider
} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import EchartSaveAs from './EchartSaveAs';
//门户组件
class EChartEditor extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            id: 0,
            title: '',
            isSys: false,
            option: null,
            value: '',
            width: '60%',
            left: '40%',
            iserror: false,
            isMouseDown: false
        }
        this.getButtons = this.getButtons.bind(this);
        this.getRightMenu = this.getRightMenu.bind(this);
        this.onRightMenuClick = this.onRightMenuClick.bind(this);
        this.onReplace = this.onReplace.bind(this);
        this.onSave = this.onSave.bind(this);
        this.onRun = this.onRun.bind(this);
    }
    componentDidMount(){
        setTimeout(()=>{
            $(window).mousemove(e => {
                if (this.state.isMouseDown) {
                    let left_rate = e.clientX / window.innerWidth;
                    left_rate = Math.min(0.9, Math.max(0.1, left_rate));
                    let left = left_rate * 100;
                    this.setState({
                        left: left + '%',
                        width: (100 - left) + '%'
                    });
                    this.onRun();
                }
            }).mouseup(() => {
                this.setState({isMouseDown: false});
            });
        },100);
    }
    getButtons(){
        const { isSys } = this.state;
        let btns = [];
        if(!isSys){
            btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zg1y16`} type='primary' onClick={this.onSave.bind(this,{})}>{getLabel(30986, '保存')}</Button>);
        }
        btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@64xb5o`} type='primary' onClick={()=>{
            this.refs.EchartSaveAs.onSetState({visible: true});
        }}>{getLabel(350, '另存为')}</Button>);
        return btns;
    }
    getRightMenu(){
        const { isSys } = this.state;
        let btns = [];
        btns.push({
            key: 'run',
            icon: <i className='icon-coms-Web-service'/>,
            content: getLabel(131308,"运行"),
        }); 
        if(!isSys){
            btns.push({
                key: 'save',
                icon: <i className='icon-coms-Web-service'/>,
                content: getLabel(30986, '保存'),
            }); 
        }
        btns.push({
            key: 'saveas',
            icon: <i className='icon-coms-Web-service'/>,
            content:getLabel(350, '另存为'),
        }); 
        btns.push({
            key: 'cancel',
            icon: <i className='icon-coms-Web-service'/>,
            content: getLabel(31129, '取消'),
        }); 
        return btns
    }
    onRightMenuClick(key){
        switch(key){
            case 'run':
                this.onRun();
                break;
            case 'save':
                this.onSave();
                break;
            case 'saveas':
                this.refs.EchartSaveAs.onSetState({visible: true});
                break;
            case 'cancel':
                this.setState({visible:false});
                break;
        }
    }
    onSave({type, title}){
        const { callback } = this.props;
        let { id, option } = this.state;
        WeaTools.callApi('/api/portal/hpEcharts/update', 'POST', {id: type == 'saveas' ? '':id, option:JSON.stringify(option), title, type}).then(result=> {
            if(result.api_status == 'success'){
                message.success(getLabel(83551, "保存成功！"));
                if(type == 'saveas'){
                    const { maxid } = result;
                    if(typeof callback === 'function'){
                        callback('add', {id: maxid, title, option});
                    }
                }else{
                    if(typeof callback === 'function'){
                        callback('update', {id, option});
                    }
                }
                this.setState({ visible: false });
            }else{
                message.error(getLabel(84544, "保存失败！"));
            }
        });
    }
    onRun(){
        this.refs.ViewEChart.onPaint();   
    }
    onReplace(js_str){
        let option;
        let app = {};
        try {
            eval(js_str);  
            if(!option || typeof option != 'object'){
                option = null;
            }
            setTimeout(()=>{
                this.setState({option, iserror: false});
                this.refs.ViewEChart.getChart().paint();
            },500);
        } catch(e) {
            window.console ? console.log(getLabel(387999,"组件异常："),e) : alert(getLabel(387999,"组件异常：")+e);
            this.setState({iserror: true});
        }
    }
    render() {
        const { title, visible, left, width, option, iserror } = this.state;
        let editor_value = "";
        if(option){
            editor_value = 'option = ' + prettyJSONStringify(option, {
                shouldExpand : function(object, level, key) {
                    if (Array.isArray(object)) return false;
                    return true;
                }
            }).replace(/"(\w+)" :/g, "$1 :");
        }
        return <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@hm212w`} 
                  title={getLabel(388000,"图表编辑")}
                  visible={visible}
                  closable={true}
                  onCancel={()=>this.setState({visible:false})}
                  icon='icon-coms-portal'
                  iconBgcolor='#1a57a0'
                  maskClosable={false}
                  buttons={this.getButtons()}
                  style={{width:document.body.clientWidth - 100,height:document.body.clientHeight - 150, overflow:'hidden'}}
                  >
                  <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@ewpnwu`} datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
                    <div id="content-container" className="portal-echart-container">
                        <EchartSaveAs ecId={`${this && this.props && this.props.ecId || ''}_EchartSaveAs@ckob04`} ref="EchartSaveAs" onSave={this.onSave}/>
                        <div id="code-container" className="echart-code-container" style={{width: left}}>
                            <div className="echart-code-top">
                                <div className="echart-code-input">
                                    <ShowTime ecId={`${this && this.props && this.props.ecId || ''}_ShowTime@mojaw4`}/>
                                    <span class={`code-info-type-${iserror ? 'error':'info'}`}>{iserror ?getLabel(388001,"编辑器内容有误！") : getLabel(388002,"图表已生成")+`}`}</span>
                                </div>
                                <div className="echart-code-run">
                                    <div onClick={this.onRun} className="echart-code-run-btn">{getLabel(131308,"运行")}</div>
                                </div>
                            </div> 
                            {/*<div className="echart-code-edit">*/}
                               {/*<AceEditor*/}
                                  {/*mode="javascript"*/}
                                  {/*name="javascript-editor"*/}
                                  {/*onChange={this.onReplace}*/}
                                  {/*fontSize={14}*/}
                                  {/*style={{width:'100%',height:'100%',padding:'10px'}}*/}
                                  {/*showPrintMargin={true}*/}
                                  {/*showGutter={true}*/}
                                  {/*highlightActiveLine={true}*/}
                                  {/*keyboardHandler={true}*/}
                                  {/*value={editor_value}*/}
                                  {/*setOptions={{*/}
                                      {/*enableBasicAutocompletion: true,*/}
                                      {/*enableSnippets: true,*/}
                                      {/*enableLiveAutocompletion: true,*/}
                                  {/*}}/>*/}
                            {/*</div>  */}
                        </div> 
                        <div id="handler-container" className="echart-handler" style={{left}} onMouseDown={()=>this.setState({isMouseDown: true})}></div> 
                        <div id="view-container" className="echart-view-container" style={{width, left}}>
                            <EChartView ecId={`${this && this.props && this.props.ecId || ''}_EChartView@5jus0h`} ref="ViewEChart" title={title} option={option}/>
                        </div>
                      </div>
                  </WeaRightMenu>
            </WeaDialog>
    }
}
let timer = null;
class ShowTime extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            time:formatTime(new Date()),
        }
    }
    componentDidMount(){
        timer = window.setInterval(()=>{
            this.setState({time: formatTime(new Date())});
        },1000);
    }
    componentWillUnmount(){
        window.clearTimeout(timer);
    }
    render(){
        return <span class="code-info-time">{this.state.time}</span>
    }
}

class ViewEChart extends React.Component {
    constructor(props) {
        super(props);
        this.getChart = this.getChart.bind(this);
        this.onPaint = this.onPaint.bind(this);
    }
    getChart(){
        return this.refs.chart;
    }
    componentDidUpdate(prevProps){
        if(!isEqual(prevProps.option, this.props.option) || prevProps.title != this.props.title){
            this.onPaint();   
        }
    }
    onPaint(){
        this.refs.chart.clear();
        this.refs.chart.paint();
    }
    render() {
        const { title, option } = this.props;
        return <WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@6pjhl1`} ref="chart" useDefault={true} chartName={title} option={option}/>
    }
}
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@mbdg74`} msg={ hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}
const EChartView = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(ViewEChart);
EChartEditor = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(EChartEditor);
export default EChartEditor;

function formatTime(time) {
    var digits = [time.getHours(), time.getMinutes(), time.getSeconds()];
    var timeStr = '';
    for (var i = 0, len = digits.length; i < len; ++i) {
        timeStr += (digits[i] < 10 ? '0' : '') + digits[i];
        if (i < len - 1) {
            timeStr += ':';
        }
    }
    return timeStr;
}

